<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Http\Request;

class Yunjin extends AbstractApi
{
    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $array = [
            'appKey'=>$bean->getSupplierNum(),
            'method' => 'direct.add',
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0'
        ];
        $recharge_array = [
            'goodsCode' =>  $bean->getGoodsId(),
            'rechargeAccount' => $bean->getAccount(),
            'buyNumber' => $bean->getRechargeNum() * $bean->getStartCharging(),
            'customerOrderNo' => $bean->getOrderNo()
        ];
        // echo  $order_no;
        $array['reqParams'] = json_encode($recharge_array);
        $array['sign'] = $this -> sign($array,$bean -> getSecretKey());
        return $array;
    }

    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key){
        //签名步骤一：把字典json序列化
        $json = json_encode( $array, 320 );
        //签名步骤二：转化为数组
        $jsonArr = preg_split('/(?<!^)(?!$)/u', $json);
        //签名步骤三：排序
        sort( $jsonArr );
        //签名步骤四：转化为字符串
        $string = implode( '', $jsonArr );
        //签名步骤五：在string后加入secret
        $string = $string . $secret_key;
        //签名步骤六：MD5加密
        $result_ = strtolower( md5( $string ) );
        return $result_;
    }
    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('orderStatus', '');
        $order_sn = $request->input('customerOrderNo', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, ['success', 'failed']))->setRechargeSuccess($status == 'success');
    }

    /**
     * @return mixed
     */
    public function apiNotifySuccess(): mixed
    {
        return response(json_encode(['code'=>0]));
    }
}
